package cj.web.login.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Base64;
import cj.utils.MD5Security;
import cj.web.rss.dao.UserInfoDAO;
import cj.web.rss.domain.UserInfo;

@Path("")
public class LoginController extends BaseController{
	
	protected static final Log logger = LogFactory.getLog(LoginController.class); 
	
	@Autowired
	private UserInfoDAO userInfoDao;
	
	@Get("")
    public String main() throws InterruptedException {
        return "/views/login.vm";
    }
	
	@Post("login")
	public String login(Model model,@Param("useraccount") String account,@Param("pwd") String pwd,
			HttpServletRequest request,HttpServletResponse response){
		try {
			UserInfo userInfo = userInfoDao.queryByAP(account);
			
			if(userInfo==null)
			{
				model.add("msg","无此用户");
				return "/views/login.vm";
			}
			else
			{
				if(userInfo.getPwd().equals((MD5Security.md5(pwd))))
				{
					List<String> memunamelis = userInfoDao.queryByMemu(userInfo.getId());
//					
					
					String memuname="@";
					for(String str:memunamelis)
					{
						memuname+=str+"@";
//						jo.put(str, str);
					}
					addCookie(response, "memuname", memuname);
					addCookie(response, "account", account);
					addCookie(response, "userId", String.valueOf(userInfo.getId()));
					addCookie(response, "name", Base64.getBase64(userInfo.getName()));
					addCookie(response, "_token_", MD5Security.returnSingKey(account));//种植的Key
				}
				else
				{
					model.add("msg","密码不正确");
					return "/views/login.vm";
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "/views/login.vm";
		}
		
		return "r:index";
    }
	
	@Get("logout")
    public String logout(HttpServletRequest request){
		return "/views/login.vm";
    }
	
	@Get("index")
    public String index() {
        return "/views/index.vm";
    }
}